//
/**
 * Filename: fig10-31_handle_TSTP.c
 * Author:   csbonkers
 * Contact:  forever65535@qq.com
 * Date:     2021/6/20
 * Description:
 *    如何处理SIGTSTP信号（作业控制信号）
 */

#include "apue.h"

static void sig_tstp(int signo){ // signal handler for SIGTSTP
  sigset_t mask;
  /*
   * ... move cursor to low left conor, rest tty mode
   */

  /*
   * unblock SIGTSTP, since it's blocked while we're handling it
   */
  sigemptyset(&mask);
  sigaddset(&mask, SIGTSTP);
  sigprocmask(SIG_UNBLOCK, &mask, NULL);

  c_signal(SIGTSTP, SIG_DFL); // reset disposition to default
  kill(getpid(), SIGTSTP); // and send hte signal to ourself

  fprintf(stderr, "kill returned");
  /*
   * we won't return from the kill until we're continuted
   */
  signal(SIGTSTP, sig_tstp); // reestablish signal handler

  /*
   * ... reset tty mode , redraw screen.
   */
}
int main(int argc, char *argv[]) {
  char buf[MAXLINE];
  // only catch sigtstp if we're running with a job-control shell
  if(c_signal(SIGTSTP, SIG_IGN) == SIG_DFL){
    c_signal(SIGTSTP, sig_tstp);
  }
  int rn = 0;
  while ((rn= read(STDIN_FILENO, buf, MAXLINE)) > 0){
    if(write(STDOUT_FILENO, buf, rn) != rn){
      err_sys("write error");
    }
  }
  if(rn < 0){
    err_sys("read error");
  }
  return 0;
}